<template>
  <h1>首页</h1>
  <div v-if="user==null">
    <router-link to="/reg">注册</router-link>
    <router-link to="/login">登录</router-link>
  </div>
  <div v-else>
    <h2>欢迎{{user.nickname}}回来!</h2>
    <router-link to="/post">
      <el-button>发微博</el-button>
    </router-link>
    <el-button @click="logout()">退出登录</el-button>
    <hr>
    <div v-for="weibo in arr">
      <h3>{{weibo.nickname}}说: {{weibo.content}}</h3>
    </div>
  </div>

</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";

  //1.看localStorage中是否有用户数据,有数据,JSON.parse转回JS对象,没数据,值为null
  const user = ref(localStorage.user?JSON.parse(localStorage.user):null);
  console.log(user.value);

  //2.实现退出登录功能
  const logout=()=>{
    if(confirm('您确认要退出登录吗?')){
      //2.1清空localStorage中保存的数据,但注意这样不会影响已经取出来的user数据
      localStorage.clear();
      //2.2还需要将user响应式变量的值重置为null,这样页面才会一起跟着重置
      user.value = null;
    }
  }
  const arr = ref([]);
  onMounted(()=>{
    axios.get("http://localhost:8080/v1/weibos/list")
  .then((response)=>{
    if (response.data.code === 2001){
      arr.value = response.data.data;
    }
  })
})
</script>
